package de.karnik.dokobu.persistence;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

public abstract class Dao <T> implements DaoInterface<T>, Serializable {

	private static final long serialVersionUID = 1L;
	
	//private EntityManager em;
	private PersistenceManager pm;

	Class<T> persistanceClass;

	protected Dao() {
		//em = EMF.get().createEntityManager();
		pm = PMF.get().getPersistenceManager();
	}
	
	public PersistenceManager getPersistenceManager() {
		return pm;
	}
	
	/*
	public EntityManager getEntityManager() {
		return this.em;
	}
	
	public void setEntityManager( EntityManager em ) {
		this.em = em;
	}*/

	public void delete( T object ) {
		pm.deletePersistent( object );
	}
	
	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		String queryString = "SELECT FROM " + getPersistanceClass().getName();
		return ( List<T> )pm.newQuery( queryString ).execute();
	}

	public void save( T object ) {
		pm.makePersistent( object );
	}

	@SuppressWarnings("unchecked")
	public List<T> getByQueryString( String queryString ) {
		return ( List<T> )pm.newQuery( queryString ).execute();
	}
	
	@SuppressWarnings( "unchecked" )
	public List<T> getByQuery( Query query ) {
		return (List<T>) query.execute();
	}
	
	@SuppressWarnings("unchecked")
	private Class<T> getPersistanceClass() {
		if ( persistanceClass == null )
			persistanceClass = ( Class )( ( ParameterizedType ) this.getClass().getGenericSuperclass() ).getActualTypeArguments()[0];

		return persistanceClass;
	}

}